import React, { useState, useEffect } from 'react';
import {
    NavBar,
    List,
    InputItem,
    Picker,
    Icon,
    Button,
    ImagePicker,
    Checkbox,
    Toast,
    WhiteSpace,
    Modal,
} from 'antd-mobile';
import _ from "lodash"
import { uploadPict, previewPict, deleteFile } from "@/api/login";

import { sexList } from "@/assets/js/dict.js"
import {
    PostTutorSignIn,
    GetTutorCheckCode,
    tutorProtocolHtml,
    GetTutorPhoneCodeForSignIn,
    GetTutorCheckPhoneForParentSignIn,
    GetTutorCheckNameForParentSignIn,
    PostTutorLogin
} from "@/api/login.js"; // login api

import { createForm } from 'rc-form';

import './signUpTutor.scss';
import { R, VOID, MAX_LENGTH_PHOTO } from "../../../assets/js/dict";

const AgreeItem = Checkbox.AgreeItem;

const Item = List.Item;
const Brief = Item.Brief;
var reImgObj = []; // 学生证照片 imgObj
var reId = []; // 学生证照片 id

const dict = {
    name: '姓名',
    school: '学校',
    code: '学号',
    gender: '性别',
    vcode: '图形码',
    phone: '手机',
    verifyCode: '验证码',
    password: '密码',
    repassword: '确认密码',
};

function SignUpTutor(props) {
    const [SignUpTutor, SetSignUpTutor] = useState({
        file: [],
        phone: ''
    });
    const [SignUpTutorRule, SetSignUpTutorRule] = useState({});
    const [isCheckout, SetIsCheckout] = useState(false);
    const [imgObject, SetImgObject] = useState({});
    const [pict, setPict] = useState([]); // 学生证照片
    const [photo, setPhoto] = useState([]); // 头像照片
    let [couldSend, updateSend] = useState(true);
    let [btn, setBtn] = useState("发送");



    //控制用户须知的显隐
    let [showVisi, setShowVisi] = useState(false);

    let [closeBtn, setCloseBtn] = useState(false);

    let [knowHtml, setKnowHtml] = useState("");

    function showNotice() {
        setShowVisi(true);
    }

    function hideNotice() {
        let target = handle['notice'];
        let scrollTop = target.scrollTop;
        target.scrollTo(0, -scrollTop);
        setShowVisi(false);
    }

    function agreeNotice() {
        hideNotice();
        SetIsCheckout(true);
    }

    // 获取注册用的图形验证码
    function axiosGetTutorCheckCode() {
        GetTutorCheckCode({}, (res) => {
            if (res.code == "000000") {
                SetImgObject(res.responseData);

                // 设置验证码过期刷新
                let timeout = res.responseData.timeout;
                if (timeout > 10) {
                    setTimeout(() => axiosGetTutorCheckCode(), (timeout - 10) * 1000);
                }
            }
        });
    }

    // 注册须知
    function axiosGetParentKnowHtml() {
        tutorProtocolHtml({},(res) => {
            if (res.code == "000000") {
                setKnowHtml(res.responseData)
            }
        });
    }

    function signin(postData) {
        try {
            postData.role = props.match.params.role;
            if(!!postData.phone){
                postData.phone = postData.phone.replace(/\s+/g, "");
            }
            if(!!postData.gender){
                postData.gender = String(postData.gender);
            }
            postData.wx_open_id = localStorage.getItem("openid");
        }catch (e) {
            console.error(e);
        }
        let userPostData = {
            username: postData.name
        };

        // 查看家教用户名是否已经注册
        GetTutorCheckNameForParentSignIn(userPostData, (res) => {
            if (res.code == '000000') {
                // 注册
                PostTutorSignIn(postData,(res) => {
                    if (res.code === "888168" && res.responseData) {
                        let info = res.responseData, words = [], seq =1;
                        for(let i in info){
                            words.push(<span key={i} style={{ marginLeft: '0.7rem' }}><strong key={i + 's'}>({seq++}){" " + info[i]}</strong><br /></span>);
                        }
                        Modal.alert('注册失败', <p style={{ textAlign: 'left' }}>{words}</p>);
                        SetSignUpTutorRule(info);

                    } else if (R.isSuccess(res)) {
                        let user = R.getData(res);
                        sessionStorage.setItem('userInfo', JSON.stringify({
                            id: user.id,
                            pass_test: false,
                            openid: user.wx_open_id,
                            username: user.name,
                            type: user.role,
                        }));

                        //执行登录
                        Toast.success("注册成功", 2, () => {
                            PostTutorLogin({ username: user.name, password: postData.password }).then(res => {
                                if (res.code === "000000") {
                                    props.history.push("/mainTutor");
                                }
                            })
                        });
                    }
                });
            } else {
                Toast.offline(res.message, 1);
            }
        });
    }


    // 注册
    function handleLogin() {
        let postData = props.form.getFieldsValue().SignUpTutor;
        console.log("handleLogin-->postData==>", postData);

        //首选检查特殊项，那些上传图片的项
        if (pict.length === 0) {
            Toast.fail("检测到学生证照片未上传图片，请完善注册信息");
            return;
        } else if (pict.length < 2) {
            Toast.fail("检测到学生证照片未上传完整，请完善注册信息");
            return;
        } else {
            postData.pict = reId.join(',');
        }

        if (photo.length === 0) {
            Toast.fail("检测到头像未上传图片，请完善注册信息");
            return;
        } else {
            postData.photo = photo[0].file_id;
        }

        if (postData.repassword !== postData.password) {
            Toast.fail("两次输入的密码不一致");
            return;
        }

        //再检查表单项
        let words = [], seq = 1, item;
        for (let key in dict) {
            item = postData[key];
            if (null === item || undefined === item || /^\s*$/.test(item)) {
                words.push(<span key={key} style={{ marginLeft: '0.7rem' }}><strong key={key + 's'}>({seq++}){" " + dict[key]}</strong><br /></span>);
            }
        }
        if (words.length > 0) {
            Modal.alert('检测到有未完成的项', <p style={{ textAlign: 'left' }}>{words}</p>,
                [{ text: '取消' }, { text: '忽略警告', onPress: () => signin(postData) }]);
        } else {
            signin(postData);
        }
    }


    // 发送验证码
    function handleGetTutorPhoneCodeForSignIn() {

        let postData = {};
        let formObj = props.form.getFieldsValue().SignUpTutor;
        let phone = formObj.phone, code = formObj.vcode;
        if (!!phone) {
            postData.phone = phone.replace(/\s+/g, "");
        } else {
            Toast.fail("请填写手机号码", 2);
            return;
        }

        postData.flag = imgObject.key;
        if (!!code) {
            postData.code = formObj.vcode;
        } else {
            Toast.fail("请填写图形验证码", 2);
            return;
        }

        GetTutorCheckPhoneForParentSignIn(postData,(res) => {
            if (R.isSuccess(res)) {
                let re = R.getData(res);
                if (re > 0) {
                    Toast.fail("手机号已经被使用，请使用其它号码", 3, VOID, false);
                } else {
                    GetTutorPhoneCodeForSignIn(postData, (res) => {
                        Toast.success("验证码已发送，请您注意查收短信", 2, VOID, false);
                        if (R.isSuccess(res)) {
                            let count = 60;
                            setBtn(`发送(${count})`);

                            //设置短信发送按键为不可以点击
                            updateSend(false);
                            let c = setInterval(() => {
                                count--;
                                if (count === 0) {
                                    clearInterval(c);
                                    setBtn("发送");

                                    //设置短信发送按键为可以点击
                                    updateSend(true);
                                } else {
                                    setBtn(`发送(${count})`);

                                    //设置短信发送按键为不可以点击
                                    updateSend(false);
                                }
                            }, 1000);
                            if (!!res[R.data]) {
                                Toast.show("验证码是：" + res[R.data], 5, false);
                            }
                        }
                    });

                    //刷新图形验证码
                    axiosGetTutorCheckCode();
                }
            } else {
                Toast.offline(res.message, 1);
            }
        });
    }

    // 把 useEffect Hook 看做 componentDidMount，componentDidUpdate 和 componentWillUnmount 这三个函数的组合
    useEffect(() => {
        axiosGetTutorCheckCode();
        axiosGetParentKnowHtml();
    }, []);

    /**
     * 压缩图片
     *@param img 被压缩的img对象
     * @param type 压缩后转换的文件类型
     * @param mx 触发压缩的图片最大宽度限制
     * @param mh 触发压缩的图片最大高度限制
     */
    function compressImg(img, type, mx, mh) {
        return new Promise((resolve, reject) => {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            const { width: originWidth, height: originHeight } = img;
            // 最大尺寸限制
            const maxWidth = mx;
            const maxHeight = mh;
            // 目标尺寸
            let targetWidth = originWidth;
            let targetHeight = originHeight;
            if (originWidth > maxWidth || originHeight > maxHeight) {
                if (originWidth / originHeight > 1) {
                    // 宽图片
                    targetWidth = maxWidth;
                    targetHeight = Math.round(maxWidth * (originHeight / originWidth))
                } else {
                    // 高图片
                    targetHeight = maxHeight;
                    targetWidth = Math.round(maxHeight * (originWidth / originHeight))
                }
            }
            canvas.width = targetWidth;
            canvas.height = targetHeight;
            context.clearRect(0, 0, targetWidth, targetHeight);
            // 图片绘制
            context.drawImage(img, 0, 0, targetWidth, targetHeight);
            canvas.toBlob(function (blob) {
                resolve(blob)
            }, type || 'image/png')
        })
    }

    // 压缩前将file转换成img对象
    function readImg(file) {
        return new Promise((resolve, reject) => {
            const img = new Image()
            const reader = new FileReader()
            reader.onload = function (e) {
                img.src = e.target.result
            }
            reader.onerror = function (e) {
                reject(e)
            }
            reader.readAsDataURL(file)
            img.onload = function () {
                resolve(img)
            }
            img.onerror = function (e) {
                reject(e)
            }
        })
    }

    const compress = async function (file, type, mx = 1000, mh = 1000) {
        const img = await readImg(file);
        let blob = await compressImg(img, file.type, mx, mh);
        return blob;
    };

    let onChange = async function (files, type, index) {
        console.log(files, type, index);
        if (type === "add") {
            if (files.length > 0) {
                let f = files[files.length - 1].file;
                if (f.size >= MAX_LENGTH_PHOTO) {
                    Toast.fail("请选择小于6兆的图片");
                    setPict([]);
                } else {
                    try {
                        const blob = await compress(f, f.type, 1000, 1000);
                        console.log("b----------->", blob);
                        f = blob;
                    } catch (e) {
                        console.error("error 压缩图片异常---> ", e);
                    }
                    uploadPict({ file: f, note: "学生证照片" }, (res) => {
                        if (res[R.code] === R.success) {
                            reImgObj.push({ file_id: res[R.data], url: previewPict(res[R.data]) });
                            reId.push(res[R.data])
                            setPict([...reImgObj]);
                        }
                    });
                }
            }
        } else if (type === "remove") {
            deleteFile({
                id: pict[index].file_id
            }).then(res => {
                if (res.code === '000000') {
                    reImgObj.splice(index, 1)
                    reId.splice(index, 1)
                    setPict([...files]);
                }
            })
        } else {
            setPict([]);
            reImgObj = []; // 学生证照片 imgObj
            reId = []; // 学生证照片 id
        }
    }

    // 上传头像
    let onChangePhoto = async function (files, type, code) {
        console.log(files, type, code);
        if (type === "add") {
            if (files.length > 0) {
                let f = files[0].file;
                if (f.size >= MAX_LENGTH_PHOTO) {
                    Toast.fail(`请选择小于${MAX_LENGTH_PHOTO / 1048576}兆的图片`);
                    setPhoto([]);
                } else {
                    try {
                        const blob = await compress(f, f.type, 1000, 1000);
                        f = blob;
                    } catch (e) {
                        console.error("error 压缩图片异常---> ", e);
                    }
                    uploadPict({ file: f, note: "用户头像" }, (res) => {
                        if (res[R.code] === R.success) {
                            let rePhoto = [{ file_id: res[R.data], url: previewPict(res[R.data]) }];
                            setPhoto(rePhoto);
                        }
                    });
                }
            }
        } else if (type === "remove") {
            deleteFile({
                id: photo[0].file_id
            }).then(res => {
                if (res.code === '000000') {
                    setPhoto([...files]);
                }
            })
        } else {
            setPhoto([]);
        }
    }

    const { getFieldProps } = props.form;
    let handle = {};

    /**
     * 点击某行使输入框获得焦点
     * @param e
     */
    function focusInput(field) {
        if (!!handle[field]) {
            handle[field].focus();
        }
    }

    /**
     * 同意协议
     * @param e
     */
    function agree(e) {
        if (e.target.checked) {
            SetIsCheckout(true);
        } else {
            SetIsCheckout(false);
        }
    }

    function back() {
        props.history.goBack();
    }

    function checkPwd(pwd){
        console.log("checkPwd--->", pwd);
        if(!!pwd){
            if(!/^(?![A-Za-z]+$)(?![\d]+$)(?![\d\W]+$)[a-zA-Z0-9\W]{6,}$/.test(pwd)){
                SignUpTutorRule.password = "密码安全性不足，密码长度至少6位，且必须由字母和数字构成";
                SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
            }else{
                SignUpTutorRule.password = "";
                SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
            }
        } 
    }

    function checkRePwd(pwd){
        console.log("checkRePwd--->", pwd);
        if(!!pwd){
            if(!/^(?![A-Za-z]+$)(?![\d]+$)(?![\d\W]+$)[a-zA-Z0-9\W]{6,}$/.test(pwd)){
                SignUpTutorRule.repassword = "密码安全性不足，密码长度至少6位，且必须由字母和数字构成";
                SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
            }else{
                let obj = props.form.getFieldsValue().SignUpTutor;
                if(pwd !== obj.password){
                    SignUpTutorRule.repassword = "两次输入的密码不一致";
                    SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
                }else{
                    SignUpTutorRule.repassword = "";
                    SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
                }
            }
        } 
    }

    function onBlur(value, field) {
        if(!!value){
            SignUpTutorRule[field] = null;
            SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
        }else {
            SignUpTutorRule[field] = dict[field] + "不能为空";
            SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
        }
    }

    function nameBlur(value) {
        onBlur(value, 'name')
    }

    function phoneBlur(value) {
        if (!!value) {
            let phone= value.replace(/\s+/g, '');
            if(/^1\d{10}$/.test(phone)){
                SignUpTutorRule['phone'] = false;
                SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
            }else {
                SignUpTutorRule['phone'] = '手机号码格式不正确';
                SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
            }
        } else {
            SignUpTutorRule['phone'] = "手机号码不能为空";
            SetSignUpTutorRule(_.cloneDeep(SignUpTutorRule));
        }
    }

    function schoolBlur(value) {
        onBlur(value, 'school')
    }

    function verifyCodelur(value) {
        onBlur(value, 'verifyCode')
    }

    function codeBlur(value) {
        onBlur(value, 'code')
    }

    function vcodeBlur(value) {
        onBlur(value, 'vcode')
    }


    return (
        <div>
            <div className="helpDetails"
                ref={(el) => {
                    handle['notice'] = el;
                }}
                style={{ overflow: 'auto', height: 'calc(100vh - 42px)', display: showVisi ? 'block' : 'none' }}
                onScroll={(event) => {
                    let target = event.target;
                    let scrollTop, maxScroll;
                    scrollTop = target.scrollTop;
                    maxScroll = target.scrollHeight - target.offsetHeight;
                    if (scrollTop >= maxScroll) {
                        setCloseBtn(true);
                    }
                }}
            >
                <div className="page-title helpDetails-tit">
                    <NavBar
                        mode="light"
                        rightContent={
                            <span key="close"
                                onClick={hideNotice}
                            >关闭</span>
                        }
                    >
                        注册须知
                    </NavBar>
                </div>
                <div className="page-content helpDetails-con" style={{ height: 'auto' }}
                    dangerouslySetInnerHTML={{ __html: knowHtml }}
                />
                <div className="form-footer  helpDetails-con" style={{ height: 'auto' }}>
                    <AgreeItem data-seed="logId" value={!!isCheckout} onChange={agree} checked={!!isCheckout}>
                        &nbsp;
                        <span>同意以上协议</span>
                    </AgreeItem>
                    <Button type="primary" onClick={agreeNotice}>{isCheckout ? '确定' : '同意并继续'}</Button>
                </div>
            </div>
            <div className="signUpTutor" style={{ display: showVisi ? 'none' : 'block' }}>
                <div className="page-title">
                    <NavBar
                        mode="light"
                        icon={<Icon type="left" />}
                        onLeftClick={back}
                    >
                        注册
                    </NavBar>
                </div>
                <div className="page-content">
                    <div className="form-box">
                        <div className="form-con">
                            <List>
                                <InputItem
                                    {...getFieldProps('SignUpTutor.name')}
                                    ref={el => {
                                        handle["name"] = el;
                                    }}
                                    clear
                                    placeholder="请输入姓名"
                                    labelNumber={6}
                                    onBlur={nameBlur}
                                    error={SignUpTutorRule.name}
                                    onErrorClick={() => {
                                        Toast.info(SignUpTutorRule.name)
                                    }}
                                >
                                    姓名
                                </InputItem>
                                <WhiteSpace size="md" />
                                <Picker
                                    data={sexList}
                                    cols={1}
                                    labelNumber={6}
                                    error={SignUpTutorRule.gender}
                                    onErrorClick={() => {
                                        Toast.info(SignUpTutorRule.gender)
                                    }}
                                    {...getFieldProps('SignUpTutor.gender', {initialValue: [sexList[0].value]})}

                                >
                                    <List.Item arrow="horizontal">性別</List.Item>
                                </Picker>
                                <WhiteSpace size="md" />
                                <InputItem
                                    labelNumber={6}
                                    onBlur={vcodeBlur}
                                    extra={<img style={{
                                        width: '90px',
                                        height: 'auto',
                                        float: 'right',
                                        marginLeft: '10px'
                                    }} src={'data:image/png;base64,' + imgObject.img}
                                        onClick={axiosGetTutorCheckCode}
                                           />}
                                    {...getFieldProps('SignUpTutor.vcode', { initialValue: '' })}
                                    placeholder="请输入图形验证码"
                                >
                                    图形码
                                </InputItem>
                                <WhiteSpace size="md" />
                                <InputItem
                                    type="phone"
                                    {...getFieldProps('SignUpTutor.phone')}
                                    ref={(el,f) => {
                                        console.log("e,f--->", el, f);
                                        handle["phone"] = el;
                                    }}
                                    placeholder="请输入手机号码"
                                    labelNumber={6}
                                    onBlur={phoneBlur}
                                    error={SignUpTutorRule.phone}
                                    onErrorClick={() => {
                                        Toast.info(SignUpTutorRule.phone);
                                    }}
                                    clear
                                >
                                    手机
                                </InputItem>
                                <WhiteSpace size="md" />
                                <InputItem
                                    type="digit"
                                    placeholder="请输入短信验证码"
                                    labelNumber={6}
                                    onBlur={verifyCodelur}
                                    error={SignUpTutorRule.verifyCode}
                                    onErrorClick={() => {
                                        Toast.info(SignUpTutorRule.verifyCode);
                                    }}
                                    extra={<Button type="primary" activeStyle={couldSend} disabled={!couldSend}
                                        loading={!couldSend} size="small" inline
                                        onClick={handleGetTutorPhoneCodeForSignIn}
                                        style={{ textAlign: 'center', top: '0', bottom: '0', marginLeft: '0.3rem' }}
                                           >
                                        {btn}
                                    </Button>}
                                    {...getFieldProps('SignUpTutor.verifyCode', { initialValue: '' })}
                                >
                                     短信验证码
                                </InputItem>
                                <InputItem
                                    {...getFieldProps('SignUpTutor.school')}
                                    clear
                                    ref={el => {
                                        handle["school"] = el;
                                    }}
                                    placeholder="请输入学校全称"
                                    labelNumber={6}
                                    onBlur={schoolBlur}
                                    error={SignUpTutorRule.school}
                                    onErrorClick={() => {
                                        Toast.info(SignUpTutorRule.school);
                                    }}
                                >
                                    学校（全称）
                                </InputItem>
                                <WhiteSpace size="md" />
                                <InputItem
                                    {...getFieldProps('SignUpTutor.code')}
                                    ref={el => {
                                        handle["code"] = el;
                                    }}
                                    clear
                                    type="text"
                                    placeholder="请输入学号"
                                    labelNumber={6}
                                    onBlur={codeBlur}
                                    error={SignUpTutorRule.code}
                                    onErrorClick={() => {
                                        Toast.info(SignUpTutorRule.code);
                                    }}
                                >
                                    学号
                                </InputItem>
                                <WhiteSpace size="md" />
                                <Item multipleLine>
                                    学生证照片（内容包括封面和信息页）
                                    <Brief>
                                        <ImagePicker
                                            files={pict}
                                            onChange={onChange}
                                            onImageClick={(index, fs) => console.log(index, fs)}
                                            selectable={pict.length < 2}
                                            multiple={false}
                                            accept="image/jpeg,image/jpg,image/png"
                                        />
                                    </Brief>
                                </Item>
                                <WhiteSpace size="md" />
                                <Item multipleLine>
                                    头像（真人头像有利于家长的信赖）
                                    <Brief>
                                        <ImagePicker
                                            files={photo}
                                            onChange={onChangePhoto}
                                            onImageClick={(index, fs) => console.log(index, fs)}
                                            selectable={photo.length < 1}
                                            multiple={false}
                                            accept="image/jpeg,image/jpg,image/png"
                                        />
                                    </Brief>
                                </Item>
                                <WhiteSpace size="md" />
                                <Item multipleLine>
                                    设置密码
                                    <Brief>
                                        <InputItem
                                            {...getFieldProps('SignUpTutor.password')}
                                            clear
                                            ref={el => {
                                                handle["password"] = el;
                                            }}
                                            placeholder="密码长度至少6位，且必须由字母和数字构成"
                                            type="password"
                                            onBlur={checkPwd}
                                            error={SignUpTutorRule.password}
                                            onErrorClick={() => {
                                                Toast.info(SignUpTutorRule.password);
                                            }}
                                        />
                                    </Brief>
                                </Item>
                                <WhiteSpace size="md" />
                                <Item multipleLine>
                                    确认密码
                                    <Brief>
                                        <InputItem
                                            {...getFieldProps('SignUpTutor.repassword')}
                                            clear
                                            ref={el => {
                                                handle["repassword"] = el;
                                            }}
                                            onBlur={checkRePwd}
                                            placeholder="请再次输入密码"
                                            type="password"
                                        />
                                    </Brief>
                                </Item>
                            </List>
                        </div>
                        <WhiteSpace size="xl" />
                        <div className="form-footer">
                            <AgreeItem data-seed="logId" value={!!isCheckout} checked={!!isCheckout} disabled>
                                &nbsp;
                                <a onClick={showNotice}>
                                    用户协议
                                </a>
                                <p style={{ margin: 0 }}>请进入详情页阅读后进行勾选</p>
                            </AgreeItem>
                            <Button type="primary" onClick={handleLogin} disabled={!isCheckout}>注册</Button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

SignUpTutor = createForm()(SignUpTutor);

export default SignUpTutor;